package edu.pku.act.test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class BTtestActivity extends Activity {
    /** Called when the activity is first created. */
	MulticastLock ml;
	InetAddress group = null;
	int port = 52121; // 端口
	MulticastSocket mss = null;  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        WifiManager wm  = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        ml = wm.createMulticastLock("jasonMulticastLock");
        ml.acquire();
        final TextView tv = (TextView) findViewById(R.id.textView1);
        final Handler handler = new Handler(new Handler.Callback() {
			
			public boolean handleMessage(Message arg0) {
				String s = (String)arg0.obj;
				tv.setText(s);
				return true;
			}
		});
        new Thread(new Runnable() {
			
			public void run() {
				new MulticastReceived().work(handler);
			}
		}).start();
        
        Button bt = (Button) findViewById(R.id.button1);
        
		try {
			group = InetAddress.getByName("224.0.0.251");
			if (!group.isMulticastAddress())
				System.out.println("Error!not multicast Address");
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} // 组播地址  
          
        
        try {
			mss = new MulticastSocket(port);
			mss.setTimeToLive(4);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // 1.创建一个用于发送和接收的MulticastSocket组播套接字对象  
        bt.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
		            EditText et = (EditText) findViewById(R.id.editText1);
		          //  et.setText("IP:"+getLocalIpAddress() + "\n"+"Mac:"+getLocalMacAddress());
		         //   et.setText(getPhoneState());
	                String message = "Phone:"+et.getText().toString();
	                byte[] buffer2 = message.getBytes(); // 2.创建一个指定缓冲区大小及组播地址和端口的DatagramPacket组播数据包对象  
	                DatagramPacket dp = new DatagramPacket(buffer2, buffer2.length, group, port);  
	                try {
						mss.send(dp);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}   
			}
		});
    }
    protected CharSequence getPhoneState() {
    	TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);  
        StringBuilder sb = new StringBuilder();  
        sb.append("\nDeviceId(IMEI) = " + tm.getDeviceId());  
        sb.append("\nDeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion());  
        sb.append("\nLine1Number = " + tm.getLine1Number());  
        sb.append("\nNetworkCountryIso = " + tm.getNetworkCountryIso());  
        sb.append("\nNetworkOperator = " + tm.getNetworkOperator());  
        sb.append("\nNetworkOperatorName = " + tm.getNetworkOperatorName());  
        sb.append("\nNetworkType = " + tm.getNetworkType());  
        sb.append("\nPhoneType = " + tm.getPhoneType());  
        sb.append("\nSimCountryIso = " + tm.getSimCountryIso());  
        sb.append("\nSimOperator = " + tm.getSimOperator());  
        sb.append("\nSimOperatorName = " + tm.getSimOperatorName());  
        sb.append("\nSimSerialNumber = " + tm.getSimSerialNumber());  
        sb.append("\nSimState = " + tm.getSimState());  
        sb.append("\nSubscriberId(IMSI) = " + tm.getSubscriberId());  
        sb.append("\nVoiceMailNumber = " + tm.getVoiceMailNumber());  
        Log.v("info", sb.toString());   
		return sb.toString();
	}
	public String getLocalIpAddress() {  
        try {  
            for (Enumeration<NetworkInterface> en = NetworkInterface  
                    .getNetworkInterfaces(); en.hasMoreElements();) {  
                NetworkInterface intf = en.nextElement();  
                for (Enumeration<InetAddress> enumIpAddr = intf  
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {  
                    InetAddress inetAddress = enumIpAddr.nextElement();  
                    if (!inetAddress.isLoopbackAddress()) {  
                        return inetAddress.getHostAddress().toString();  
                    }  
                }  
            }  
        } catch (SocketException ex) {  
            Log.e("WifiPreference IpAddress", ex.toString());  
        }  
        return null;  
    }  
      
    public String getLocalMacAddress() {  
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
        WifiInfo info = wifi.getConnectionInfo();  
        return info.getMacAddress();  
    }  
    @Override
    protected void onStop() {
    	Log.v("Onstop","ml,release");
    	ml.release();
    	
    	super.onStop();
    }
}